package com.xcm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.DateFormatConstant;
import com.xcm.constant.OperationLogConstant;
import com.xcm.constant.PageConstant;
import com.xcm.dao.DeviceInfoMapper;
import com.xcm.dao.FirmWareMapper;
import com.xcm.model.TbDeviceInfo;
import com.xcm.model.TbDeviceUpgrade;
import com.xcm.model.TbOperationLog;
import com.xcm.model.dto.FirmWareListDTO;
import com.xcm.model.vo.DeviceInfoListVO;
import com.xcm.model.vo.FirmWareListVO;
import com.xcm.page.PageInfo;
import com.xcm.service.FirmWareService;
import com.xcm.service.OperationLogService;
import com.xcm.util.DateUtils;
import com.xcm.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName FirmWareServiceImpl
 * @Description 固件管理
 * @Author HanQinrui
 * @Date 2018/5/7 10:00
 * @Version 1.0
 **/
@Service("firmWareService")
public class FirmWareServiceImpl implements FirmWareService {
    @Autowired
    private FirmWareMapper firmWareMapper;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    /**
     * 获取固件分页列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<FirmWareListVO> listByPage(Integer pageNum, Integer pageSize) {
        //设置默认值
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        Page<FirmWareListDTO> page = firmWareMapper.listByPage();
        if (page == null) {
            return new PageInfo<>(pageNum, pageSize, 0, Lists.newArrayList());
        }
        //把Page转为PageInfo
        PageInfo<FirmWareListVO> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(page.getTotal());
        // 把DTO转为VO，并把时间戳转为字符串
        List<FirmWareListDTO> firmWareListDTOList = page.getResult();
        List<FirmWareListVO> firmWareListVOList = Lists.newArrayList();
        for (FirmWareListDTO firmWareListDTO : firmWareListDTOList) {
            FirmWareListVO firmWareListVO = new FirmWareListVO();
            firmWareListVO.setDeviceUpgradeId(firmWareListDTO.getDeviceUpgradeId());
            firmWareListVO.setName(firmWareListDTO.getName());
            firmWareListVO.setActive(firmWareListDTO.getActive());
            firmWareListVO.setModel(firmWareListDTO.getModel());
            firmWareListVO.setSize(firmWareListDTO.getSize());
            firmWareListVO.setSoftwareVersionDescription(firmWareListDTO.getSoftwareVersionDescription());
            firmWareListVO.setUpgradeType(firmWareListDTO.getUpgradeType());
            firmWareListVO.setUrl(firmWareListDTO.getUrl());
            firmWareListVO.setVersionCode(firmWareListDTO.getVersionCode());
            firmWareListVO.setVersionName(firmWareListDTO.getVersionName());
            Long updateTime = firmWareListDTO.getUpdateTime();
            if(updateTime == null) {
                firmWareListVO.setUpdateTime("");
            } else {
                firmWareListVO.setUpdateTime(DateUtils.longTimeStampToStringDate(updateTime, DateFormatConstant.LONG_DATE_FORMAT_STR));
            }
            firmWareListVOList.add(firmWareListVO);
        }
        pageInfo.setList(firmWareListVOList);
        return pageInfo;
    }

    /**
     * 获取更新固件下终端列表
     * @param hardVersion 固件版本号
     * @param deviceStatus 在线状态 0.在线; 1.离线
     * @param deviceModel 机型
     * @param groupCode 分组编码
     * @param province 省
     * @param city 市
     * @param area 区
     * @param deviceUpgradeId 固件ID
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<DeviceInfoListVO> updateFirmWareListByPage(String hardVersion, String deviceStatus, String deviceModel, String groupCode,
                                                               String province, String city, String area, String deviceUpgradeId,
                                                               Integer pageNum, Integer pageSize) {
        //设置默认值
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        Page<DeviceInfoListVO> page = firmWareMapper.updateFirmWareListByPage(hardVersion, deviceStatus, deviceModel, groupCode, province, city, area, deviceUpgradeId);
        if(page == null ) {
            return new PageInfo<>(pageNum, pageSize, 0, Lists.newArrayList());
        }
        PageInfo<DeviceInfoListVO> pageInfo = new PageInfo<>();
        pageInfo.setList(page.getResult());
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    /**
     * 查询所有固件版本号
     * @return
     */
    @Override
    public List<String> listAllFirmWareVersionCode() {
        return firmWareMapper.listAllFirmWareVersionCode();
    }

    /**
     * 根据查询条件获取在线终端总数
     *
     * @param hardVersion  固件版本号
     * @param deviceModel 机型
     * @param groupCode   分组编码
     * @param province    省
     * @param city        市
     * @param area        区
     * @return
     */
    @Override
    public Long getFirmWareDeviceOnlineCount(String hardVersion, String deviceModel, String groupCode, String province, String city, String area) {
        System.out.println("hardVersion: " + hardVersion);
        return firmWareMapper.getDeviceOnlineCount(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, hardVersion, deviceModel, groupCode, province, city, area);
    }

    /**
     * 根据查询条件获取离线终端总数
     *
     * @param hardVersion  固件版本号
     * @param deviceModel 机型
     * @param groupCode   分组编码
     * @param province    省
     * @param city        市
     * @param area        区
     * @return
     */
    @Override
    public Long getFirmWareDeviceOfflineCount(String hardVersion, String deviceModel, String groupCode, String province, String city, String area) {
        return firmWareMapper.getDeviceOnlineCount(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, hardVersion, deviceModel, groupCode, province, city, area);
    }
    /**
     * 根据终端Id修改固件升级Id
     *
     * @param deviceInfoIds   终端Id(多个Id之间用逗号隔开)
     * @param deviceUpgradeId 固件Id
     * @param user
     * @param request
     * @return 更新成功条数
     */
    @Override
    public int updateFirmWareUpgradeIdByDeviceInfoIds(String deviceInfoIds, Integer deviceUpgradeId, JSONObject user, HttpServletRequest request) {
        int i = 0;
        for(String deviceInfoId : deviceInfoIds.split(",")) {
           Integer retCount = firmWareMapper.updateFirmWareUpgradeIdByDeviceInfoIds(deviceInfoId,deviceUpgradeId);
           i = retCount.intValue() + i;
        }
        //保存操作日志
        TbOperationLog operationLog = new TbOperationLog();
        operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
        operationLog.setOperationContent("终端:" + deviceInfoIds + "更新固件: " + deviceUpgradeId + ",成功" + i + "条,失败" + (deviceInfoIds.split(",").length - i) + "条");
        operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        // TODO: 2018/4/9 处理用户ID和IP地址
        //展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
        operationLog.setUserName(user.getString("userName"));
        operationLog.setRealName(user.getString("realName"));
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
        return i;
    }

    /**
     * 根据固件Id查询固件名称和版本号
     *
     * @param deviceUpgradeId
     * @return
     */
    @Override
    public FirmWareListVO getFirmWareByDeviceUpgradeId(String deviceUpgradeId) {
        return firmWareMapper.getFirmWareByDeviceUpgradeId(deviceUpgradeId);
    }

    /**
     * 新增固件
     *
     * @param deviceUpgrade 新增的固件对象
     * @param user
     * @param request
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    @Override
    public int saveFirmware(TbDeviceUpgrade deviceUpgrade, JSONObject user, HttpServletRequest request) {
        int row = 0;
        deviceUpgrade.setUpdateTime(System.currentTimeMillis());
        deviceUpgrade.setActive(BusinessConstant.DEVICE_UPGRADE_FORCE_NO);
        deviceUpgrade.setUpgradeType(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE);
        deviceUpgrade.setIsdelete(BusinessConstant.DEVICE_UPGRADE_IS_DELETED_NO);
        int count = countByParams(deviceUpgrade);
        if (count > 0) {
            return -1;
        }
        row = firmWareMapper.saveFirmware(deviceUpgrade);
        //保存操作日志
        TbOperationLog operationLog = new TbOperationLog();
        operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_FIRMWARE);
        operationLog.setOperationContent("新增固件:" + deviceUpgrade.getName());
        operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        // TODO: 2018/4/9 处理用户ID和IP地址
        //展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
        operationLog.setUserName(user.getString("userName"));
        operationLog.setRealName(user.getString("realName"));
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
        return row;
    }

    /**
     * 检查固件是否已存在
     * @param deviceUpgrade 待检查的固件
     * @return
     */
    @Override
    public boolean canSave(TbDeviceUpgrade deviceUpgrade) {
        int count = firmWareMapper.countByParams(deviceUpgrade);
        return count == 0;
    }

    /**
     * 检查终端是否重复升级
     * @param deviceInfoIds
     * @param deviceUpgradeId
     * @return
     */
    @Override
    public HashMap checkRepeat(String deviceInfoIds, Long deviceUpgradeId) {
        // 返回结果Map
        HashMap<String, Object> resultMap = new HashMap<>();
        // 重复的终端Id,多个Id之间用逗号隔开
        StringBuilder repeatDeviceInfoIds = new StringBuilder();
        // 可以更新的终端Id,多个Id之间用逗号隔开
        StringBuilder unRepeatDeviceInfoIds = new StringBuilder();

        for(String deviceInfoId : deviceInfoIds.split(",")) {
           TbDeviceInfo tbDeviceInfo = deviceInfoMapper.getDeviceInfoById(Long.valueOf(deviceInfoId));
           if(tbDeviceInfo != null) {
               Long firmWareUpgradeId = tbDeviceInfo.getFirmWareUpgradeId();
               if(deviceUpgradeId.equals(firmWareUpgradeId)) {
                   // 如果终端当前升级固件Id等于页面上选择的升级Id
                   repeatDeviceInfoIds.append(deviceInfoId + ",");
               } else {
                   unRepeatDeviceInfoIds.append(deviceInfoId + ",");
               }
           }
        }
        resultMap.put("repeatDeviceInfoIds",repeatDeviceInfoIds);
        resultMap.put("unRepeatDeviceInfoIds",unRepeatDeviceInfoIds);
        return resultMap;
    }

    /**
     * 统计固件
     *
     * @param deviceUpgrade 待检查的固件
     * @return
     */
    @Override
    public int countByParams(TbDeviceUpgrade deviceUpgrade) {
        return firmWareMapper.countByParams(deviceUpgrade);
    }

    /**
     * 升级固件
     *
     * @param deviceUpgrade 升级的固件
     * @param user
     * @param request
     * @return
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    @Override
    public int promoteFirmWare(TbDeviceUpgrade deviceUpgrade, JSONObject user, HttpServletRequest request) {
//        // TODO 远程下载文件到本地（暂时不用）
//        //根据固件url地址更新固件文件
//        if (StringUtils.isBlank(deviceUpgrade.getUrl())) {
//            throw new ServiceException("升级包地址不能为空");
//        }
//        Map<String, String> resultMap = fileService.downloadRemoteFirmwareFile(deviceUpgrade.getUrl(), customProperties.getFirmwareFileSavePath());
//        String fileDownloadPath = resultMap.get("fileDownloadPath");
//        String size = resultMap.get("size");
//        if (StringUtils.isBlank(fileDownloadPath)) {
//            throw new ServiceException("升级包下载失败");
//        }
//        if (StringUtils.isBlank(size) || Double.parseDouble(size) == 0D) {
//            throw new ServiceException("升级包无内容");
//        }
        deviceUpgrade.setUpgradeType(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE);
        deviceUpgrade.setUpdateTime(System.currentTimeMillis());
        deviceUpgrade.setActive(BusinessConstant.DEVICE_UPGRADE_FORCE_YEE);
        int row = firmWareMapper.promoteFirmWare(deviceUpgrade);
        //升级操作日志
        TbOperationLog operationLog = new TbOperationLog();
        operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
        operationLog.setOperationContent("升级固件:" + deviceUpgrade.getName());
        operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        // TODO: 2018/4/9 处理用户ID和IP地址
        //展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
        operationLog.setUserName(user.getString("userName"));
        operationLog.setRealName(user.getString("realName"));
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
        return row;
    }
}
